package com.example.imitation_webchat_demo.fragment;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import android.app.Fragment;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.imitation_webchat_demo.R;
import com.example.imitation_webchat_demo.adapter.AddressListAdapter;
import com.example.imitation_webchat_demo.adapter.MineAdapter;
import com.example.imitation_webchat_demo.controller.AddressHandler;
import com.example.imitation_webchat_demo.entity.MineItem;
import com.example.imitation_webchat_demo.entity.T_userInfo;
import com.example.imitation_webchat_demo.model.AssortView;
import com.example.imitation_webchat_demo.model.AssortView.OnTouchAssortListener;
import com.example.imitation_webchat_demo.model.MyComparator;
import com.example.imitation_webchat_demo.util.AppUtils;
import com.example.imitation_webchat_demo.util.PinyinUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

// 通讯录fragment
public class AddressListFragment extends Fragment {
	@ViewInject(R.id.address_list_expandable_listview)
	private ExpandableListView listView;

	@ViewInject(R.id.address_list_view)
	private TextView sumView;

	@ViewInject(R.id.address_list_assort)
	private AssortView assortView;

	@ViewInject(R.id.address_listview)
	private ListView listView_1;

	@ViewInject(R.id.address_searchview)
	private EditText searchText;

	@ViewInject(R.id.address_search_clear)
	private ImageButton searchClearBtn;

	private AddressListAdapter adapter;
	// private List<FriendItem> list;
	//
	// private List<String> groupList;
	// private List<List<FriendItem>> childList;
	// private List<FriendItem> childListItem;

	private String username;
	private MineAdapter adapter_1;
	private List<MineItem> list_1;

	private String friendshipInfo;
	private List<T_userInfo> list;
	private List<String> groupList;
	private List<List<T_userInfo>> childList;
	private List<T_userInfo> childListItem;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_address_list, container,
				false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		ViewUtils.inject(this, getActivity());

		getIntentData(); // 获取intent传过来的置
		initComponent(); // 初始化控件
		addListener(); // 添加监听
	}

	// 获取intent传过来的值
	public void getIntentData() {
		username = AppUtils.getUsernameFromShare(this.getActivity());

		friendshipInfo = getActivity().getIntent().getStringExtra(
				"friendshipInfo");
		if (friendshipInfo != null) {    //如果是从登陆页面跳转过来的
			try {
				friendshipInfo = URLDecoder.decode(friendshipInfo, "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			Gson gson = new Gson();
			Type listType = new TypeToken<LinkedList<T_userInfo>>() {
			}.getType();
			list = gson.fromJson(friendshipInfo, listType);
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getUser_remark() == null) {
					list.get(i).setUser_remark(list.get(i).getNickname());
				}
			}
		}
	}

	// 初始化控件
	public void initComponent() {
		list_1 = new ArrayList<MineItem>();
		MineItem mineItem = new MineItem(R.drawable.a_1, "通知");
		list_1.add(mineItem);
		mineItem = new MineItem(R.drawable.a_9, "群聊");
		list_1.add(mineItem);
		adapter_1 = new MineAdapter(getActivity(), list_1);
		listView_1.setAdapter(adapter_1);

		MyComparator comparator = new MyComparator();
		Collections.sort(list, comparator); // friendItem按name字段排序

		groupList = new ArrayList<String>();
		childList = new ArrayList<List<T_userInfo>>();

		for (int i = 0; i < list.size(); i++) {
			char char1 = PinyinUtil.getPinYin(list.get(i).getUser_remark())
					.charAt(0);
			String firstChar = String.valueOf(char1);

			if ((char1 > 'Z' || char1 < 'A') && char1 != '#') {
				list.get(i).setUser_remark("?" + list.get(i).getUser_remark());
				firstChar = "?";
			}
			if (!groupList.contains(firstChar)) {
				groupList.add(firstChar);
			} else {
				continue;
			}
		}
		for (int i = 0; i < groupList.size(); i++) {
			childListItem = new ArrayList<T_userInfo>();
			for (int j = i; j < list.size(); j++) {
				char char1 = PinyinUtil.getPinYin(list.get(j).getUser_remark())
						.charAt(0);
				if (String.valueOf(char1).equals(groupList.get(i))) {
					if (char1 == '?') {
						T_userInfo item1 = list.get(j);
						item1.setUser_remark(item1.getUser_remark()
								.substring(1));
						childListItem.add(item1);
						continue;
					}
					childListItem.add(list.get(j));
				}
			}
			childList.add(childListItem);
		}

		adapter = new AddressListAdapter(this.getActivity(), groupList,
				childList);
		adapter.setHandler(new AddressHandler() {
			@Override
			public void onReceive(boolean isEmpty) {
				// 展开所有分组
				expandGroup();
				if (isEmpty) {
					listView_1.setVisibility(View.VISIBLE);
				} else {
					listView_1.setVisibility(View.GONE);
				}
			}
		});
		listView.setAdapter(adapter);

		// 展开所有分组
		expandGroup();

		// 字母按键回调
		assortView.setOnTouchAssortListener(new OnTouchAssortListener() {
			View layoutView = LayoutInflater.from(
					AddressListFragment.this.getActivity()).inflate(
					R.layout.alert_dialog_menu_layout, null);
			TextView text = (TextView) layoutView.findViewById(R.id.content);
			PopupWindow popupWindow;

			public void onTouchAssortListener(String str) {
				int index = groupList.indexOf(str);
				if (index != -1) {
					listView.setSelectedGroup(index);
				}
				if (popupWindow != null) {
					text.setText(str);
				} else {
					popupWindow = new PopupWindow(layoutView, 120, 120, false);
					// 显示在Activity的根视图中心
					popupWindow.showAtLocation(AddressListFragment.this
							.getActivity().getWindow().getDecorView(),
							Gravity.CENTER, 0, 0);
				}
				text.setText(str);
			}

			public void onTouchAssortUP() {
				if (popupWindow != null)
					popupWindow.dismiss();
				popupWindow = null;
			}
		});
	}

	// 添加监听
	public void addListener() {
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Toast.makeText(
						AddressListFragment.this.getActivity(),
						PinyinUtil.getPinYin(list.get(position)
								.getUser_remark()), Toast.LENGTH_LONG).show();
			}
		});

		searchText.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				String str = s.toString();
				adapter.getFilter().filter(s);
				if (str != null && str.length() != 0) {
					searchClearBtn.setVisibility(View.VISIBLE);
				} else {
					searchClearBtn.setVisibility(View.INVISIBLE);
				}
			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
	}

	// 点击搜索栏里的删除按钮，删除搜索栏中的文本
	@OnClick(R.id.address_search_clear)
	private void clear(View view) {
		searchText.setText("");
	}

	// 展开所有分组
	private void expandGroup() {
		for (int i = 0, length = adapter.getGroupCount(); i < length; i++) {
			listView.expandGroup(i);
		}
	}
}